import axios from 'axios'
import { MessageBox } from 'element-ui'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, cancelAxios } from '@/utils/auth'

/*
|--------------------------------------------------------------------------
| 默认 API 调用Service
|--------------------------------------------------------------------------
| 用户调用GoLang API
|
*/

window.canCancelAxios = []

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    const whiteList = [] // 白名单
    if (config.url && whiteList.every(item => !config.url.includes(item))) {
      config.cancelToken = new axios.CancelToken(function (c) {
        window.canCancelAxios.push({ key: config.key || '', cancel: c })
      })
    }
    return config
  },
  error => {
    // do something with request error
    console.log('service.interceptors.response Error', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 0, it is judged as an error.
    if (res.code > 0) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 20103 || res.code === 50012 || res.code === 50014) {
        // to re-login
        // 如果token无效，取消后续请求
        cancelAxios()
        MessageBox.confirm('您已注销，可以取消以保留在该页面上，或者再次登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }).catch(err => {
          console.log('取消注销', err)
        })
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log('service.interceptors.response Error' + error) // for debug
    // Message({
    //   message: '服务器请求失败，请稍后再试',
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
